package developer.算法.二分查找.搜索插入位置;

/**
 * @author zhangyongkang
 * @time 2024/6/12 14:47
 * @description 给定一个排序数组和一个目标值，在数组中找到目标值，并返回其索引。如果目标值不存在于数组中，返回它将会被按顺序插入的位置。
 * <p>
 * 请必须使用时间复杂度为 O(log n) 的算法。
 * <p>
 * <p>
 * <p>
 * 示例 1:
 * <p>
 * 输入: nums = [1,3,5,6], target = 5
 * 输出: 2
 * <p>
 * 示例 2:
 * <p>
 * 输入: nums = [1,3,5,6], target = 2
 * 输出: 1
 * 示例 3:
 * <p>
 * 输入: nums = [1,3,5,6], target = 7
 * 输出: 4
 * <p>
 * <p>
 * 1 2 3 3 3 5
 * <p>
 * 提示:
 * <p>
 * 1 <= nums.length <= 104
 * -104 <= nums[i] <= 104
 * nums 为 无重复元素 的 升序 排列数组
 * -104 <= target <= 104
 * <p>
 * 《二分查找法》
 * 1 2 3 4
 * target = 2
 * if(mid == 2 ){
 * return idx;
 * }
 */
public class Solution_self {
    public static void main(String[] args) {
        System.out.println(searchIndex(new int[]{1, 3, 5, 6}, 5));
        System.out.println(searchIndex(new int[]{1, 3, 5, 6}, 3));
        System.out.println(searchIndex(new int[]{1, 3, 5, 6}, 7));
        System.out.println(searchIndex(new int[]{1, 3, 5, 6}, 0));

        System.out.println("------");
        Solution3 solution3 = new Solution3();
        System.out.println(solution3.searchIndex(new int[]{1, 3, 5, 6}, 5));
        System.out.println(solution3.searchIndex(new int[]{1, 3, 5, 6}, 3));
        System.out.println(solution3.searchIndex(new int[]{1, 3, 5, 6}, 7));
        System.out.println(solution3.searchIndex(new int[]{1, 3, 5, 6}, 0));
    }


    static class Solution3 {
        public int searchIndex(int[] nums, int target) {
            int ans = nums.length;
            int left = 0;
            int right = nums.length - 1;

            if (target <= nums[left]) {
                return 0;
            }
            if (target > nums[right]) {
                return nums.length;
            }
            // 1 2 3 4  target = 5
            while (left <= right) {
                int midIdx = left + (right - left) / 2;
                int midVal = nums[midIdx];
                if (target >= midVal) {

                    left = midIdx + 1;
                    ans = midIdx;
                } else {
                    right = midIdx - 1;
                }
            }
            return ans;
        }
    }

    public static int searchIndex(int[] nums, int target) {
        int n = nums.length;
        int left = 0, right = n - 1, ans = n;//边界情况  数组的最大值小于 target 情况

        while (left <= right) {
            int mid = left + (right - left) / 2;
            int midVal = nums[mid];
            if (midVal >= target) {//边界情况  数组的最大值小于 target 情况
                right = mid - 1;
                ans = mid;
            } else {
                left = mid + 1;
            }

        }
        return ans;


    }

}
